const express = require('express');
const userModel = require('../db/models/UserModel');
const { RES_CODE } = require('../utils/constants');
const formidable = require('formidable');
const { resolve } = require('path');
const md5 = require('md5')

const router = express.Router();

// 获取用户列表接口 - 需要验证token
router.get('/user/:page/:limit', async (req, res) => {
    let { page, limit } = req.params;

    // 3  5
    let skip = (page - 1) * limit;

    try {
        let datas = await userModel.find().skip(skip).limit(limit);

        let count = await userModel.count();

        res.json({
            code: RES_CODE.SUCCESS,
            data: {
                users: datas,
                total: count
            },
            message: "获取列表成功"
        })
    } catch (e) {
        res.json({
            code: RES_CODE.SERVER_ERROR,
            message: '服务器错误' + e
        })
    }

    // console.log(data,count);

    // res.send('页码:'+page+'，单页显示条数:'+limit);
})

// 获取单个用户信息
router.get('/user', async (req, res) => {

    // 获取id - 获取地址栏的查询字符串
    let { id } = req.query;

    try {
        let user = await userModel.findById(id);

        if (user) {
            res.json({
                code: RES_CODE.SUCCESS,
                data: user,
                message: '获取用户成功'
            })
        } else {
            res.json({
                code: RES_CODE.DATA_ERROR,
                message: 'id参数错误'
            })
        }

    } catch (e) {
        res.json({
            code: RES_CODE.SERVER_ERROR,
            message: '服务器错误' + e
        })
    }

});


// 删除用户
router.delete('/user/:id', async (req, res) => {

    // 拿到id
    let { id } = req.params;

    try {
        // 删除数据库中对应的数据
        await userModel.deleteOne({ _id: id });
        res.json({
            code: RES_CODE.SUCCESS,
            message: '删除成功'
        })
    } catch (e) {
        res.json({
            code: RES_CODE.SERVER_ERROR,
            message: '服务器错误' + e
        })
    }

})


// 解析表单数据对象
let readFile = formidable({
    uploadDir: resolve(__dirname, '../public/upload'),
    keepExtensions: true,
    maxFieldsSize:1024*1024
});

// 添加用户
router.post('/user', (req, res) => {

    // 解析req对象 带来的数据 - 文件 + 字段数据
    readFile.parse(req, async (err, fields, files) => {

        // 判断失败
        if (err) {
            return res.json({
                code: RES_CODE.DATA_ERROR,
                message: '图片上传失败'
            });
        }

        try {
            // 表单name属性
            let { username, pwd } = fields;

            // 判断此用户名是否已被注册
            let user = await userModel.findOne({ username });

            if (user) {
                return res.json({
                    code: RES_CODE.DATA_ERROR,
                    message: '用户名已存在'
                })
            }

            // 表单字段name
            let { profile } = files;

            // 数据库只存文件的路径
            let imgUrl = '/upload/' + profile.newFilename;

            // 插入数据
            let newUser = await userModel.create({
                username: username,
                pwd: md5(pwd),
                profile: imgUrl
            })


            res.json({
                code: RES_CODE.SUCCESS,
                data: newUser,
                message: '添加成功'
            })
        } catch (e) {
            res.json({
                code: RES_CODE.SERVER_ERROR,
                message: '服务器错误' + e
            })
        }
    })
})

// 更新用户
router.put('/user', (req, res) => {

    // 解析req对象 带来的数据 - 文件 + 字段数据
    readFile.parse(req, async (err, fields, files) => {

        // 判断失败
        if (err) {
            return res.json({
                code: RES_CODE.DATA_ERROR,
                message: '图片上传失败'
            });
        }

        try {
            // 传入用户id
            let { username, _id } = fields;

            if(!_id){
               return res.json({
                    code:RES_CODE.DATA_ERROR,
                    message:'id未传入'
                })
            }

            let user = await userModel.findOne({ _id });

            if(!user)return;

            let { profile } = files;

            // 数据库只存文件的路径
            let imgUrl = '/upload/' + profile.newFilename;

            // 更新数据 - option 1. 查询条件 _id
            let newUser = await userModel.updateOne({_id},{
                username: username,
                profile: imgUrl
            })


            res.json({
                code: RES_CODE.SUCCESS,
                message: '更新成功'
            })

        } catch (e) {
            res.json({
                code: RES_CODE.SERVER_ERROR,
                message: '服务器错误' + e
            })
        }
    })

})


module.exports = router;